<template>
  <div class="edit-profile-page">
    <h2>编辑资料</h2>
    <form @submit.prevent="handleSubmit">
      <!-- 昵称 -->
      <div class="form-group">
        <label>昵称</label>
        <input v-model="formData.petName" type="text" required />
      </div>

      <!-- 邮箱 -->
      <div class="form-group">
        <label>邮箱</label>
        <input v-model="formData.email" type="email" required />
      </div>

      <!-- 头像上传组件 -->
      <div class="form-group">
        <label>头像</label>
        <UploadImage
            :propImageUrl="formData.headImage"
            @imageChange="handleImageChange"
        />
      </div>

      <!-- 操作按钮 -->
      <div class="actions">
        <button type="submit">保存</button>
        <button type="button" @click="GoToIndex">返回个人中心</button>
      </div>
    </form>
  </div>
</template>

<script>
import axios from 'axios'; // 引入 axios
import UploadImage from '@/components/UploadImage.vue';
import router from "@/router";

export default {
  name: 'EditProfile',
  components: {
    UploadImage,
  },
  data() {
    return {
      formData: {
        petName: '',
        email: '',
        headImage: '',
      },
    };
  },
  mounted() {
    this.fetchUserInfo();
  },
  methods: {
    async fetchUserInfo() {
      try {
        let token = sessionStorage.getItem("token");
        const response = await axios.get('http://localhost:9090/user/info', {
          headers: {
            'Authorization': `Bearer ${token}` // 将 token 添加到 Authorization 头
          }
        });
        const { petName, email, headImage } = response.data.data;
        this.formData.petName = petName;
        this.formData.email = email;
        this.formData.headImage = headImage;
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    },
    async handleSubmit() {
      try {
        // 发送请求并接收返回的数据
        let token = sessionStorage.getItem("token");
        const response = await axios.post('http://localhost:9090/user/update',
            this.formData,
            {
              headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
              }
            });
        console.log('Response Data:', response.data); // 打印返回的数据
        // 判断返回的 code 字段
        if (response.data.code === 200) {
          alert('资料更新成功！');
          this.$router.push('/profile'); // 返回个人中心
        } else {
          alert(`资料更新失败：${response.data.message}`); // 显示后端返回的错误信息
        }
      } catch (error) {
        console.error('更新资料失败:', error);
        alert('请求失败，请检查网络或稍后重试'); // 显示网络或请求错误
      }
    },
    handleImageChange(imageUrl) {
      this.formData.headImage = imageUrl;
    },
    GoToIndex() {
      router.push({ name: 'ProfilePage' })
    },
  },
};
</script>

<style scoped>
.edit-profile-page {
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.form-group input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.actions {
  display: flex;
  gap: 10px;
}

.actions button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.actions button[type='submit'] {
  background-color: #007bff;
  color: #fff;
}

.actions button[type='submit']:hover {
  background-color: #0056b3;
}

.actions button[type='button'] {
  background-color: #6c757d;
  color: #fff;
}

.actions button[type='button']:hover {
  background-color: #5a6268;
}
</style>